<template>
	<div class="cart">
	<ion-header>
	  <ion-toolbar>
	    <ion-buttons slot="start">
	      <ion-back-button></ion-back-button>
	    </ion-buttons>
	    <ion-title>购物车</ion-title>
	  </ion-toolbar>
	</ion-header>
    <ion-content class="cartcon">
        <div class="cartlist" v-if="shopCartList !=null && shopCartList.length > 0" ref="shopCart">
            <div class="listbox2"  v-for="(shopCart,index) in shopCartList" :key="index">
                <div class="box_radio">
                    <label class="radio"><input type="checkbox" checked class="checkCart"  :id="index" @click="clickCheckbox" /></label>
                </div>
                <div class="box_left">
                    <img :src="shopCart.imageUrl" v-if="shopCart && shopCart.imageUrl !=null"/>
                    <img src="../assets/images/p1.jpg" v-else/>
                    <div class="left_con">
                       <button @click="selectGiveType(index)" class="btn">
                           <i class="iconfont icon-zhankai"></i><span>{{giftGiveTypes[shopCart.saleType]}}</span>
                       </button>
                        <h3 class="tit">{{shopCart.goodsName}}</h3>
                        <span class="spec">{{shopCart.goodSpec}}</span>
                        <p class="price">
                            <strong class="cprice">￥<em>{{shopCart.amount}}</em></strong>
                            <span class="uprice">{{shopCart.salePrice}}元/{{shopCart.unit}}</span>
                        </p>
                    </div>
                </div>
                <div class="box_right">
                    <!--<div class="numberbox">-->
                        <!--<button type="button" id="reduce" @click="reduce()">-</button>-->
                        <!--<input type="number" id="text" v-model="products.number">-->
                        <!--<button type="button" id="add" @click="add()">+</button>-->
                    <!--</div>-->
                    <van-stepper :max="shopCart.stockNum" v-model="shopCart.buyNumber" @change="countSingleAmount(index)" />
                </div>
            </div>
				</div>
        <div class="blankDiv " v-else>
           <span > 还没产品，快去添加吧 ~  </span> 
           <br>
           <ion-button @click="openPage" color="primary">去商城</ion-button>
        </div>
    </ion-content>
		<div class="floatbox">
				<div class="tit">
					<p>合计：<span>￥<i>{{totalAmount}}</i></span></p>
					<!-- <h3>收款方式</h3> -->
				</div>
				<!-- <div class="con">
						 <button v-for="(type) in paymentTypes" :class="[paymentType==type.value?'active':'']"
										 @click="checkPaymentType(type.value)" :key="type.value">{{type.name}}
							</button>
				</div> -->
			</div>
		    <div class="footbar" ref="footBtnRef">
		        <div class="foot_radio">
		            <label class="radio"><input type="checkbox" checked class="checkAllBtn" id="r0" @click="selectAll"/> 全选</label>
		        </div>
		        <button class="foot_btn1" @click="deleted">
		            <span class="txt">删除</span>
		        </button>
		        <button class="foot_btn3" @click="createOrder">
		            <span class="txt">生成订单</span>
		        </button>
		    </div>
		<van-actionsheet
		  v-model="showGiveTypeAction"
		  :actions="giftGiveType"
		  @select="checkGiveType"
		/>
	</div>
</template>
<script>
import { Stepper, Actionsheet } from "vant";
import router from "../router";
import baseUtil from "@/utils/baseUtil.js";
import {
  shopCartList,
  updateToCart,
  deletedShopCart,
  updateSaleType,
  createOrder,
  orderDetail
} from "@/api/vanProducts";
export default {
  name: "cart",
  components: {
    [Stepper.name]: Stepper,
    [Actionsheet.name]: Actionsheet
  },
  data() {
    return {
      showGiveTypeAction: false,
      shopCartList: [],
      paymentTypes: [
        {
          value: "WEIXIN",
          name: "微信"
        },
        {
          value: "ALI_PC_DIRECT",
          name: "支付宝"
        },
        {
          value: "CASH",
          name: "现金"
        }
      ],
      giftGiveType: baseUtil.saleTypeList,
      giftGiveTypes: baseUtil.saleType,
      paymentType: "WEIXIN",
      checkedIds: [],
      totalAmount: 0,
      giveTypeCartIndex: 0
    };
  },
  methods: {
    openPage() {
      this.$router.push({ name: "vanTypes" });
    },
    //全选/全不选
    selectAll(e) {
      this.checkedIds = [];
      this.totalAmount = 0;
      // console.log("selectAll-e:", e);
      let checkeds = this.$refs.shopCart.getElementsByClassName("checkCart");
      for (let i = 0, len = checkeds.length; i < len; i++) {
        let cart = checkeds[i];
        // console.log('selectAll-checkeds[i]',cart);
        cart.checked = e.target.checked;
        if (cart.checked) {
          const cartPro = this.shopCartList[cart.id];
          this.checkedIds.push(cartPro.id);
          this.totalAmount = (
            parseFloat(cartPro.amount) + parseFloat(this.totalAmount)
          ).toFixed(2);
        }
      }
    },
    //点击复选框
    clickCheckbox(e) {
      // console.log('clickCheckbox-e:',e.target);
      this.countTotalAmount();
    },
    //去选择赠品赠送方式
    selectGiveType(index) {
      console.log("selectGiveType-index:", index);
      this.giveTypeCartIndex = index;
      this.showGiveTypeAction = true;
    },
    //选择赠品赠送方式
    async checkGiveType(item) {
      console.log("checkGiveType-item:", item);
      this.showGiveTypeAction = false;
      let shopcart = this.shopCartList[this.giveTypeCartIndex];
      if (shopcart.saleType == item.value) return;
      let param = { shopCartId: shopcart.id, saleType: item.value };
      let resp = await updateSaleType(param);
      console.log("checkGiveType-resp:", resp);
      if (baseUtil.isNotBlankObjs(resp) && resp.code != null) {
        const color = resp.code == 0 ? "success" : "warning";
        const msg =
          resp.code == 0
            ? "修改成功"
            : resp.code == 400
              ? resp.warnMessage
              : "修改出现异常，请刷新页面重试，或联系管理员";
        this.presentToast(msg, color);
        if (resp.code == 0) {
          const newShopCart = resp.data.shopCart;
          shopcart.saleType = item.value;
          shopcart.salePrice = newShopCart.salePrice;
          shopcart.amount =
            parseFloat(newShopCart.salePrice) *
            parseFloat(newShopCart.buyNumber).toFixed(2);
          this.countTotalAmount();
        } else {
        }
      }
    },
    //统计选中商品 总金额
    countTotalAmount() {
      // console.log('countTotalAmount=================');
      this.checkedIds = [];
      this.totalAmount = 0;
      let checkeds = this.$refs.shopCart.getElementsByClassName("checkCart");
      let checkAll = true;
      for (let i = 0, len = checkeds.length; i < len; i++) {
        let cart = checkeds[i];
        // console.log('countTotalAmount-checkeds[i]',cart);
        if (cart.checked) {
          const cartPro = this.shopCartList[cart.id];
          this.checkedIds.push(cartPro.id);
          this.totalAmount = (
            parseFloat(cartPro.amount) + parseFloat(this.totalAmount)
          ).toFixed(2);
        } else {
          checkAll = cart.checked;
        }
      }
      //如果已全选，则全选按钮选中
      let checkAllBtn = this.$refs.footBtnRef.getElementsByClassName(
        "checkAllBtn"
      )[0];
      checkAllBtn.checked = checkAll;

      // console.log('clickCheckbox-checkAllBtn:',checkAllBtn);
    },
    // 计算单个商品金额
    async countSingleAmount(index) {
      // console.log('countSingleAmount-index:',index);
      let cartPro = this.shopCartList[index];
      // console.log('countSingleAmount-cartPro:',cartPro);
      //long vanSpecId, Double count, double salePrice, TerminalSaleType saleType
      let addProduct = {
        vanSpecId: cartPro.vanSpecId,
        count: cartPro.buyNumber,
        salePrice: cartPro.salePrice,
        saleType: cartPro.saleType
      };
      let resp = await updateToCart(addProduct);
      // console.log('addToCart-resp:',resp);
      if (baseUtil.isNotBlankObjs(resp) && resp.code == 0) {
        cartPro.amount = (
          parseFloat(cartPro.buyNumber) * parseFloat(cartPro.salePrice)
        ).toFixed(2);
        this.countTotalAmount();
      }
    },
    //选择支付方式
    checkPaymentType(paymentType) {
      this.paymentType = paymentType;
      // console.log('checkPaymentType:',this.paymentType);
    },
    //删除购物车商品
    async deleted() {
      console.log("deleted-checkedIds:", this.checkedIds);

      if (this.checkedIds == null || this.checkedIds.length == 0) {
        this.presentToast("请选择您要删除的商品 ~ ", "primary");
        return;
      }
      let delIds = this.checkedIds.join(",");
      console.log("deleted-delIds:", delIds);
      let param = { ids: delIds };
      let resp = await deletedShopCart(param);
      console.log("deleted-resp:", resp);
      if (baseUtil.isNotBlankObjs(resp) && resp.code == 0) {
        this.presentAlert("删除成功！");
      }
    },
    // 创建订单
    async createOrder() {
      if (this.checkedIds == null || this.checkedIds.length == 0) {
        this.presentToast("请选择选购的商品", "primary");
        return;
      }
      let ids = this.checkedIds.join(",");
      console.log("createOrder====ids:", ids);
      let param = { shopCartIds: ids, paymentType: this.paymentType };
      let resp = await createOrder(param);
      console.log("createOrder===resp:", resp);
      if (baseUtil.isNotBlankObjs(resp)) {
        if (resp.code == 0) {
          this.$router.push({
            name: "orderDetail",
            query: { orderNumber: resp.data.orderNumber }
          });
          return;
        }
        if (resp.code == 400) {
          this.presentToast(resp.warnMessage, "warning");
          return;
        }
        this.presentToast("操作异常 ！", "warning");
      }
    },
    //初始化购物车数据
    async initShopCart() {
      let resp = await shopCartList();
      // console.log('initShopCart-resp:',resp);
      if (baseUtil.isNotBlankObjs(resp) && baseUtil.isNotBlankObjs(resp.data)) {
        this.shopCartList = resp.data;
        this.$nextTick(function() {
          this.countTotalAmount();
        });
      }
    },
    //弹出警告 提示等信息
    //color:"primary", "secondary", "tertiary", "success", "warning", "danger", "light", "medium", and "dark"
    async presentToast(msg, color) {
      color = color == null || color == "" ? "success" : color;
      const toast = await this.$ionic.toastController.create({
        message: msg,
        duration: 1000,
        color: color,
        position: "top"
      });
      toast.present();
    },
    //alert提示
    presentAlert(msg) {
      return this.$ionic.alertController
        .create({
          header: "提示",
          // subHeader: 'Subtitle',
          message: msg,
          buttons: [
            {
              text: "确认",
              handler: () => {
                this.initShopCart();
              }
            }
          ]
        })
        .then(a => a.present());
    }
  },
  mounted() {
    this.initShopCart();
  }
};
</script>

<style>
.cart .ion-padding,
[padding] {
  padding: 0;
}

.cartlist {
  height: auto;
  overflow: hidden;
  padding-bottom: 6rem;
}

.cart_price {
  background: #fff;
  padding: 0.5rem 0.75rem;
  height: auto;
  overflow: hidden;
  text-align: left;
}

.cart_price {
  font-size: 0.75rem;
  color: #999;
}

.cart_price span {
  color: #ff3300;
}

.cart_price i {
  font-size: 1.2rem;
  font-weight: bold;
  font-style: normal;
}

.cart_pay {
  background: #fff;
  height: auto;
  overflow: hidden;
  margin: 0.5rem 0 3rem 0;
}

.cart_pay .tit {
  padding: 0.75rem 0.75rem;
  height: auto;
  overflow: hidden;
  text-align: left;
  border-bottom: 0.05rem #eeeeee solid;
  font-size: 0.8rem;
  color: #666;
}

.cart_pay .con {
  padding: 1rem 0.75rem;
  height: auto;
  overflow: hidden;
  display: flex;
  justify-content: space-between;
}

.cart_pay button {
  flex: 1;
  padding: 0 0.75rem;
  height: 2.5rem;
  line-height: 2.5rem;
  overflow: hidden;
  background: #eee;
  display: block;
  color: #333;
  font-size: 0.85rem;
  margin: 0 0.5rem 0.5rem 0;
  border-radius: 0.3rem;
}

.cart_pay button.active {
  background: #f93;
  color: #fff;
}
</style>